import React, {useState, useEffect} from 'react'
import {List, ImagePicker, Toast, InputItem, Button, TextareaItem, Picker} from 'antd-mobile'
import {createForm} from 'rc-form'
import {MyNavBar} from '@/components'
import {useAreaHook, useHttpHook} from '@/hooks'
import {Http} from '@/utils'

function Edit(props) {
  const [ files, setFiles ] = useState([])

  const {getFieldProps, validateFields} = props.form

  const [ userInfo ] = useHttpHook({url: '/userInfo/my', method: 'get'})

  const [area] = useAreaHook()

  const handleChange = (files) => {
    if (files[0]?.file?.size / 1024 / 1024 > 5) {
      Toast.fail('图片大小不得超过5M')
      return
    }
    setFiles(files)
  }

  useEffect(() => {
    setFiles([ {url: userInfo?.avatar} ])
  }, [ userInfo ])

  const handleSubmit = () => {
    validateFields(async (err, val) => {
      if (err || !files.length) {
        Toast.fail('请将信息补充完整')
        return
      }
      if (val.areaId.length !== 4 && val.areaId.length) {
        Toast.fail('必须选择四级区域')
        return
      }
      const result = await Http({
        url: '/userInfo/my', method: 'put', body: {
          avatar: files[0].url,
          firstName: val.firstName,
          secondName: val.secondName,
          phoneNum: val.phoneNum,
          address: val.address,
          description: val.description,
          areaId: val.areaId.length === 4 ? val.areaId[3] : undefined
        }
      })

      if (result) {
        Toast.success('修改成功')
      }
    })
  }

  console.info(area)

  return (
    <div className='user-edit'>
      <MyNavBar title={'信息设置'}/>
      <List>
        <List.Item>
          <ImagePicker files={files} selectable={files.length < 1} onChange={handleChange}/>
        </List.Item>
        <List>
          <InputItem {...getFieldProps('firstName', {
            initialValue: userInfo?.firstName
          })} placeholder='姓'>姓：</InputItem>
          <InputItem {...getFieldProps('secondName', {
            initialValue: userInfo?.secondName
          })} placeholder='名'>名：</InputItem>
          <InputItem {...getFieldProps('phoneNum', {
            initialValue: userInfo?.phoneNum
          })} placeholder='电话号码'>电话号码：</InputItem>
          <InputItem {...getFieldProps('address', {
            initialValue: userInfo?.address
          })} placeholder='地址'>地址：</InputItem>
          <TextareaItem rows={3} title='个人描述：' {...getFieldProps('description', {
            initialValue: userInfo?.description
          })} placeholder='个人描述'></TextareaItem>
        </List>
        <Picker extra="请选择(可选)"
                data={area}
                title="地区"
                {...getFieldProps('areaId', {initialValue:[1,2,3,4]})}
                cols={4}
        >
          <List.Item arrow="horizontal">请选择地区</List.Item>
        </Picker>
        <Button type='warning' onClick={handleSubmit} style={{marginTop: '20px'}}>修改</Button>
      </List>
    </div>
  )
}

export default createForm()(Edit)
